import Request from '@/utils/luch-request/index.js'

const http = new Request()
http.setConfig((config) => { /* 设置全局配置 */
  config.baseUrl = 'http://localhost:8282/'//测试服务
  
  config.header = { 
    ...config.header
  }
  return config
})

/**  
 * 自定义验证器，如果返回true 则进入响应拦截器的响应成功函数(resolve)，否则进入响应拦截器的响应错误函数(reject)
 * @param { Number } statusCode - 请求响应体statusCode（只读）
 * @return { Boolean } 如果为true,则 resolve, 否则 reject
 */

const getTokenStorage = () => {
	let token = ''
	try{
		token ='Bearer ' + uni.getStorageSync('App-Token')
	}catch(e){
		//TODO handle the exception
	}
	return token
}
// 有默认，非必写
http.validateStatus = (statusCode) => {
  return statusCode === 200
}

http.interceptor.request((config, cancel) => { /* 请求之前拦截器 */
  if(config.cType != undefined){
	  if(config.cType == 'App-Token'){
		  let orgnization=uni.getStorageSync("orgnization")
		  let userInfo=uni.getStorageSync("userInfo")
		  let username =  userInfo.username
		  // config.header = { 
		  //   ...config.header,
		  //   // Authorization: ''
		  // }
		  let userName = encodeURI(username)
		  if(orgnization){
			  config.header = {
				...config.header,
				HZ: orgnization,
				USERNAME: userName
			  }
		  } else {
			  config.header = { 
				...config.header
			  }
		  }
	  }else{ 
		  config.header = {
		    "Content-Type":config.cType,
		    Authorization: getTokenStorage()
		  }
	  }
	
  }else{
	config.header = {
	  ...config.header,
	   Authorization: getTokenStorage()
	}
  }
  /*
  if (!token) { // 如果token不存在，调用cancel 会取消本次请求，但是该函数的catch() 仍会执行
    cancel('token 不存在') // 接收一个参数，会传给catch((err) => {}) err.errMsg === 'token 不存在'
  }
  */
  return config
})
//用户token过期时，重新请求接口刷新token,用户refreshToken失效，让用户重新登录
const refreshTokenFun = () =>{
	let refreshToken=uni.getStorageSync("refreshToken")
	let token=uni.getStorageSync("token")
	uni.request({ 
		url: '', //示例
	    data: {refreshToken:refreshToken},
	    header: {
	       "Content-Type": "application/json",
	       // "Authorization": token
	    },
		method:"POST",
	    success: (res) => {
	        if (res.data.code == 200) {
				let newRefreshToken = res.data.data.refreshToken
				let newToken = res.data.data.token
	        	uni.removeStorage({
	        	    key: 'refreshToken',
	        	    success: (res)=> {
	        			uni.setStorageSync("refreshToken",newRefreshToken)
	        	    }
	        	});
	        	uni.removeStorage({
	        	    key: 'App-Token',
	        	    success: (res)=> {
	        			uni.setStorageSync("token",'Bearer '+newToken)
	        	    }
	        	});

	        }else if(res.data.code == 704){
				uni.showToast({
					title:"您的登录已过期，请重新登录！",
					icon:'none',
					duration:3000
				})
				uni.clearStorage()
				uni.setStorageSync("sortStatus",true)
				uni.switchTab({url:"/pages/me/index.vue"})
			}
	    }
	})
}
// 必须使用异步函数，注意
http.interceptor.response(async (response) => { /* 请求之后拦截器 */
  return response
}, (response) => {// 请求错误
	if (response.statusCode == 401) {
		uni.clearStorage()
		uni.navigateTo({url: "/"});
		uni.showToast({
			title:"登录过期，请重新登录！",
			icon:'none',
			duration:5000
		})
	 }
	 if (response.statusCode == 500) {
		 uni.showModal({
		 	title: '提示',
		 	content:  response.data.explain,
		 	success:  (res) => {}
		 })
	  }
	// #ifdef APP-PLUS || MP-WEIXIN || MP-BAIDU
		uni.getNetworkType({
			success:  (res)=> {
				if(res.networkType == 'none') {
					uni.showLoading({title: '无网络'});
				}
				let setT = null;
				setT = setTimeout(()=>{
					clearTimeout(setT)
					uni.hideLoading()
				}, 3000)
			}
		});
	// #endif
    return response
})

export {
  http
}
